# @Time: 2021/6/23
# @Dev: TJ

import os
from loguru import logger


def log_msg_format(task=None, module=None, func=None, flag=None,  msg=None) -> str:
    """
    统一日志内容风格
    :param task: 任务名
    :param module: 模块名
    :param func: 函数名
    :param flag: 标记值
    :param msg: 消息
    :return: 组装好的日志
    """
    logs = [str(x) for x in [f"Task-<{task}>", module, func, flag, msg] if x]
    return ' | '.join(logs)


def add_logger(platform_name: str = ''):
    base_dir = os.path.join('logs', platform_name)
    config_dict = dict(
        rotation="0:00",
        format="{time:YYYY-MM-DD at HH:mm:ss} | {level} | {thread.name} | {module}:{function}:{line} - {message}",
        retention="7 days",
        encoding="utf-8",
        compression="zip",
        # enqueue=True,  # 多线程日志
    )

    # 日志过滤器
    def filter_key_and_level(key, level):
        def fn(m):
            return m["level"].name == level  # 按等级分离
            # return m["level"].name == level and m["extra"].get("ext_key", "") == key  # 按模块分离

        return fn

    logger.add(
        os.path.join(base_dir, "error_{time:YYYY-MM-DD}.log"),
        level="ERROR",
        filter=filter_key_and_level(platform_name, "ERROR"),
        **config_dict
    )
    logger.add(
        os.path.join(base_dir, "warning_{time:YYYY-MM-DD}.log"),
        level="WARNING",
        filter=filter_key_and_level(platform_name, "WARNING"),
        **config_dict
    )
    logger.add(
        os.path.join(base_dir, "info_{time:YYYY-MM-DD}.log"),
        level="INFO",
        # filter=filter_key_and_level(platform_name, "INFO"),
        **config_dict
    )
    logger.add(
        os.path.join(base_dir, "debug_{time:YYYY-MM-DD}.log"),
        level="DEBUG",
        filter=filter_key_and_level(platform_name, "DEBUG"),
        **config_dict
    )
    return logger.bind(ext_key=platform_name)


if __name__ == '__main__':
    module_name = str(os.path.basename(__file__)).split('.')[0]  # 模块名
    logger = add_logger(module_name)
    logger.debug(log_msg_format(task='0', module='debug', func='func_debug', flag='flag', msg=123))
    logger.info(log_msg_format(task='1', module='info', flag='flag', msg='info'))
    logger.warning(log_msg_format(task='2', module='warning', flag='flag', msg=dict(warning='warning')))
    logger.error(log_msg_format(task='3', module='error', flag='flag', msg=Exception('error')))
